package com.iwomy.envpro.platform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.CaseFormat;
import com.iwomy.envpro.admin.api.entity.SysTenant;
import com.iwomy.envpro.admin.api.feign.RemoteTenantService;
import com.iwomy.envpro.common.core.constant.SecurityConstants;
import com.iwomy.envpro.common.core.util.R;
import com.iwomy.envpro.common.data.tenant.TenantContextHolder;
import com.iwomy.envpro.platform.VO.AirRealTimeDataVO;
import com.iwomy.envpro.platform.constant.CpEnum;
import com.iwomy.envpro.platform.constant.TpEnum;
import com.iwomy.envpro.platform.dto.HistoricalDataDTO;
import com.iwomy.envpro.platform.entity.AirFactorEntity;
import com.iwomy.envpro.platform.entity.AirMonitorEquipmentEntity;
import com.iwomy.envpro.platform.entity.AirRealTimeDataEntity;
import com.iwomy.envpro.platform.entity.AirSiteEntity;
import com.iwomy.envpro.platform.service.AirFactorService;
import com.iwomy.envpro.platform.service.HistoricalDataService;
import com.iwomy.envpro.platform.utils.DataLimitUtil;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.*;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Field;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 空气实时数据表
 *
 * @author pig
 * @date 2023-08-31 09:28:08
 */
@Service
public class HistoricalDataServiceImpl implements HistoricalDataService {
	@Resource
	private MongoTemplate mongoTemplate;
	@Resource
	private AirFactorService airFactorService;
	@Resource
	private RemoteTenantService remoteTenantService;

	@Override
	public List<JSONObject> list(HistoricalDataDTO historicalDataDTO) throws Exception {
		List<AirFactorEntity> airFactorEntities = airFactorService.listByIds(historicalDataDTO.getFactorIdList());
		List<String> codeList = airFactorEntities.stream().map(AirFactorEntity::getCode).collect(Collectors.toList());
		ProjectionOperation po = Aggregation.project()
				.and("monitorEquipmentId").as("monitorEquipmentId")
				.and("recordTime").as("recordTime");

		TpEnum instance = TpEnum.getInstance(historicalDataDTO.getTp());
		for (AirFactorEntity airFactorEntity : airFactorEntities) {
			po = po.and((TpEnum.REAl_TIME.equals(instance) )? airFactorEntity.getCode()+".Rtd" : airFactorEntity.getCode()+".Avg").as(airFactorEntity.getEnName());
		}
		Long tenantId = TenantContextHolder.getTenantId();
		R<SysTenant> details = remoteTenantService.details(tenantId,SecurityConstants.FROM_IN);
		SysTenant sysTenant = Optional.ofNullable(details.getData()).get();
		Aggregation aggregation = Aggregation.newAggregation(
				Aggregation.match(Criteria.where("monitorEquipmentId").is(historicalDataDTO.getMonitorEquipmentId())
						.and("recordTime").gte(DataLimitUtil.convertMilliseconds(historicalDataDTO.getDt0(), sysTenant))
						.lte(DataLimitUtil.convertMilliseconds(historicalDataDTO.getDt1(), sysTenant) + 1000l))
				, po);

		AggregationResults<JSONObject> results = mongoTemplate.aggregate(aggregation, instance.getName(), JSONObject.class);
		List<JSONObject> resultList = results.getMappedResults();

		/*Query query = Query.query(Criteria.where("monitorEquipmentId").is(historicalDataDTO.getMonitorEquipmentId())
				.andOperator(Criteria.where("recordTime").gte(historicalDataDTO.getDt0().toInstant(ZoneOffset.of("+8")).toEpochMilli())
						.lte(historicalDataDTO.getDt1().toInstant(ZoneOffset.of("+8")).toEpochMilli())));
		Field fields = query.fields();
		codeList.stream().forEach(x -> {
			String rtdByReportCode = CpEnum.getRtdByReportCode(x);
			if (StrUtil.isNotEmpty(rtdByReportCode))
				fields.include(rtdByReportCode);
		});
		fields.include("recordTime");
		query.with(Sort.by(Sort.Direction.DESC, "recordTime"));
		//查询所有在线设备，获取所有在线设备
//		TpEnum instance = TpEnum.getInstance(historicalDataDTO.getTp());
		List<JSONObject> jsonObjects = mongoTemplate.find(query, JSONObject.class, "test_collection");*/
		return resultList;
	}


	/**
	 * code转数据库字段
	 *
	 * @param codeList
	 * @return
	 */
	private List<String> codeToVar(List<String> codeList) {
		return codeList.stream().map(x -> CpEnum.getVarByReportCode(x)).collect(Collectors.toList());
	}


}